//
//  YHCircularView.swift
//  Adorbee
//
//  Created by amovision on 2024/12/4.
//

import UIKit

open class YHCircularView: UIView {
  public var isClockwise = true
  public var lineWidth: CGFloat = 6
  public var progressColor: UIColor = .systemBlue
  public var trackColor: UIColor = .systemBlue.alpha(0.2)
  public var progress: Float = 0 {
    didSet {
      setNeedsDisplay()
    }
  }
    
  public convenience init(lineWidth: CGFloat, progress: UIColor = Theme.light, track: UIColor = .clear, isClockwise: Bool = true) {
    self.init(frame: .zero)
    backgroundColor = .clear
    self.lineWidth = lineWidth
    self.progressColor = progress
    self.trackColor = track
    self.isClockwise = isClockwise
  }
    
  private var startAngle: CGFloat {
    isClockwise ? -.pi / 2 : -.pi / 2 + CGFloat(1 - progress) * .pi * 2
  }
    
  private var endAngle: CGFloat {
    isClockwise ? -.pi / 2 + CGFloat(progress) * .pi * 2 : -.pi / 2
  }

  public override func draw(_: CGRect) {
    let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
    let trackPath = UIBezierPath(ovalIn: rect)
    trackPath.lineWidth = lineWidth
    trackColor.setStroke()
    trackPath.stroke()
    let progressPath = UIBezierPath(arcCenter: [bounds.width / 2].point, radius: (bounds.width - lineWidth) / 2, startAngle: startAngle, endAngle: endAngle, clockwise: isClockwise)
    progressPath.lineWidth = lineWidth
    progressPath.lineCapStyle = .round
    progressColor.setStroke()
    progressPath.stroke()
  }
}
